
//这个函数在整个wps加载项中是第一个执行的
function OnAddinLoad(ribbonUI){
    if (typeof (wps.ribbonUI) != "object"){
		wps.ribbonUI = ribbonUI
    }
    
    if (typeof (wps.Enum) != "object") { // 如果没有内置枚举值
        wps.Enum = WPS_Enum
    }

    wps.PluginStorage.setItem("EnableFlag", false) //往PluginStorage中设置一个标记，用于控制两个按钮的置灰
    wps.PluginStorage.setItem("ApiEventFlag", false) //往PluginStorage中设置一个标记，用于控制ApiEvent的按钮label
    return true
}

var WebNotifycount = 0;
function OnAction(control) {
    const eleId = control.Id
    switch (eleId) {
        case "btnCheckDuplicates":
            {
                let rgn = Application.Selection
                row_1 = rgn.Row                     //获取选中区域的起始行
                col_1 = rgn.Column                  //获取选中区域的起始列

                //获取选中区域的宽度和高度
                height = rgn.Rows.Count
                width = rgn.Columns.Count

                row = row_1 + height - 1    //获取选中区域的结束行
                col = col_1 + width - 1     //获取选中区域的结束列

                const doc = wps.Application.ActiveWorkbook
                ext = doc.Name.split(".").pop()
                if (ext == "xlsx") {
                    if (rgn.Rows.Count == 1048576) {
                        e = rgn.End(4)      //End(4)表示下方向
                        row = e.Row
                    }
                    if (rgn.Columns.Count == 16384) {
                        e = rgn.End(2)      //End(2)表示右方向
                        col = e.Column
                    }
                }
                if (ext == "xls") {
                    if (rgn.Rows.Count == 65536) {
                        e = rgn.End(4)      //End(4)表示下方向
                        row = e.Row
                    }
                    if (rgn.Columns.Count == 256) {
                        e = rgn.End(2)      //End(2)表示右方向
                        col = e.Column
                    }
                }
                rgn = wps.Range(wps.Cells.Item(row_1,col_1), wps.Cells.Item(row,col))

                rgn.Interior.ColorIndex = 0

                cellCount = rgn.Cells.Count
                var values = rgn.Value2.join().split(",")
                
                for (i = 0; i < cellCount; i++) {
                    if (values[i]) {
                        for (j = 1; j <= cellCount - i; j++) {
                            if(values[i] == values[i + j])
                            {
                                rgn.Cells.Item(i+1).Interior.ColorIndex = 45 
                                rgn.Cells.Item(i+1+j).Interior.ColorIndex = 45
                            }
                        }

                    }
                }
            }
            break;



        case "btnShowMsg":
            {
                const doc = wps.Application.ActiveWorkbook
                if (!doc) {
                    alert("当前没有打开任何文档")
                    return
                }
                alert(doc.Name)
                // alert("当前文档的名称是：" + doc.Name)
                break
            }
            break;
        case "btnIsEnbable":
            {
                let bFlag = wps.PluginStorage.getItem("EnableFlag")
                wps.PluginStorage.setItem("EnableFlag", !bFlag)
                
                //通知wps刷新以下几个按饰的状态
                wps.ribbonUI.InvalidateControl("btnIsEnbable")
                wps.ribbonUI.InvalidateControl("btnShowDialog") 
                wps.ribbonUI.InvalidateControl("btnShowTaskPane") 
                //wps.ribbonUI.Invalidate(); 这行代码打开则是刷新所有的按钮状态
                break
            }
        case "btnShowDialog":
            wps.ShowDialog(GetUrlPath() + "/ui/dialog.html", "这是一个对话框网页", 400 * window.devicePixelRatio, 400 * window.devicePixelRatio, false)
            break
        case "btnShowTaskPane":
            {
                let tsId = wps.PluginStorage.getItem("taskpane_id")
                if (!tsId) {
                    let tskpane = wps.CreateTaskPane(GetUrlPath() + "/ui/taskpane.html")
                    let id = tskpane.ID
                    wps.PluginStorage.setItem("taskpane_id", id)
                    tskpane.Visible = true
                } else {
                    let tskpane = wps.GetTaskPane(tsId)
                    tskpane.Visible = !tskpane.Visible
                }
            }
            break
        case "btnApiEvent":
            {
                let bFlag = wps.PluginStorage.getItem("ApiEventFlag")
                let bRegister = bFlag ? false : true
                wps.PluginStorage.setItem("ApiEventFlag", bRegister)
                if (bRegister){
                    wps.ApiEvent.AddApiEventListener('NewWorkbook', OnNewDocumentApiEvent)
                }
                else{
                    wps.ApiEvent.RemoveApiEventListener('NewWorkbook', OnNewDocumentApiEvent)
                }

                wps.ribbonUI.InvalidateControl("btnApiEvent") 
            }
            break
        case "btnWebNotify":
            {
                let currentTime = new Date()
                let timeStr = currentTime.getHours() + ':' + currentTime.getMinutes() + ":" + currentTime.getSeconds()
                wps.OAAssist.WebNotify("这行内容由wps加载项主动送达给业务系统，可以任意自定义, 比如时间值:" + timeStr + "，次数：" + (++WebNotifycount), true)
            }
            break
        case "btnString2Number":
            {
                let rgn = Application.Selection
                rgn.NumberFormatLocal = "G/通用格式"

                if (rgn.Count == 1048576 || rgn.Count == 65536) {
                    console.log("当前选中的单元格数量1048576个")
                    e = rgn.End(4) //End(4)表示下方向
                    row = e.Row
                    col = e.Column
                    for (let i = 1; i <= row; i++) {
                        wps.Cells.Item(i, col).Formula = wps.Cells.Item(i, col).Formula
                    }
                    return true
                }else{
                    console.log("当前选中的单元格数量:" + rgn.Count)
                    // console.log(rgn.Value())
                    for (let i = 1; i <= rgn.Count; i++) {
                        wps.Cells.Item(i).Value2 = wps.Cells.Item(i).Value()
                    }
                    return true
                }
            }
            break
        case "btnNumber2String":
            {
                let rgn = Application.Selection
                rgn.NumberFormatLocal = "@";
                iCount = rgn.Count
                if (iCount == 1048576 || iCount == 65536) {
                    console.log("当前选中的单元格数量1048576个")
                    e = rgn.End(4) //End(4)表示下方向
                    row = e.Row
                    col = e.Column
                    for (let i = 1; i <= row; i++) {
                        wps.Cells.Item(i, col).Value2 = wps.Cells.Item(i, col).Value()
                    }
                }else{
                    console.log("当前选中的单元格数量:" + iCount)
                    for (let i = 1; i <= iCount; i++) {
                        temp = rgn.Item(i).Value()
                        rgn.Item(i).ClearContents()
                        // console.log(temp)
                        rgn.Item(i).Value2 = temp
                    }
                }
                

                // if (rgn.Count == 1048576) {
                //     console.log("当前选中的单元格数量1048576个")
                // }
            }
            break
        
        case "btnToast":
            path = wps.ActiveWorkbook.FullName.split("\\")
            console.log(path)
            wps.ActiveSheet.Copy()
            fileName = path.pop().split(".")
            path.push(wps.ActiveSheet.Name + "." + fileName.pop())
            console.log(path)
            path = path.join("\\")
            console.log(path)

            // wps.ShowDialog(GetUrlPath() + "/ui/test.html", "这是一个对话框网页", 400 * window.devicePixelRatio, 400 * window.devicePixelRatio, false)
            wps.ActiveWorkbook.Close(true, path)
            break
        case "btnExam":
            {
                init = OnInit();
                OnAddPage()
                OnPageSetup()
                init.forEach((item, index) => {
                    stdName = item["姓名"]
                    stdClass = item["班级"]
                    stdExamHall = item["考场"]
                    stdExamSeat = item["座位号"]
                    stdExamNum = item["考号"]
                    if(index%3==0){
                        OnExportBorder(2*index + 1)
                        OnInputData(stdName,stdClass,stdExamHall,stdExamSeat,stdExamNum,wps.Cells.Item(6*Math.floor(index/3)+1,2))
                    }
                    if(index%3==1){
                        OnInputData(stdName,stdClass,stdExamHall,stdExamSeat,stdExamNum,wps.Cells.Item(6*Math.floor(index/3)+1,5))
                    }else{
                        OnInputData(stdName,stdClass,stdExamHall,stdExamSeat,stdExamNum,wps.Cells.Item(6*Math.floor(index/3)+1,8))
                    }

                });
            }
            break
        case "btnQueue":
            const doc = wps.Application.ActiveWorkbook
            ext = doc.Name.split(".").pop()
            let rgn = Application.Selection
            if (ext == "xlsx") {
                if (rgn.Rows.Count == 1048576 || rgn.Columns.Count == 16384) {
                    alert("请不要选择整行或者整列进行填充")
                    break
                }
            }
            if (ext == "xls") {
                if (rgn.Rows.Count == 65536 || rgn.Columns.Count == 256) {
                    alert("请不要选择整行或者整列进行填充")
                    break
                }
            }
            iCount = rgn.Count
            for (i = 1; i <= iCount; i++) {
                rgn.Cells.Item(i).Value2 = i
            }
            break

        default:
            break
    }
    return true
}

function GetImage(control) {
    const eleId = control.Id
    switch (eleId) {
        case "btnShowMsg":
            return "images/1.svg"
        case "btnShowDialog":
            return "images/2.svg"
        case "btnShowTaskPane":
            return "images/3.svg"
        case "btnString2Number":
            return "images/4.svg"
        case "btnNumber2String":
            return "images/4.svg"
        default:
            ;
    }
    return "images/newFromTemp.svg"
}

function OnGetEnabled(control) {
    const eleId = control.Id
    switch (eleId) {
        case "btnShowMsg":
            return true
            break
        case "btnShowDialog":
            {
                let bFlag = wps.PluginStorage.getItem("EnableFlag")
                return bFlag
                break
            }
        case "btnShowTaskPane":
            {
                let bFlag = wps.PluginStorage.getItem("EnableFlag")
                return bFlag
                break
            }
        default:
            break
    }
    return true
}

function OnGetVisible(control){
    return true
}

function OnGetLabel(control){
    const eleId = control.Id
    switch (eleId) {
        case "btnIsEnbable":
        {
            let bFlag = wps.PluginStorage.getItem("EnableFlag")
            return bFlag ?  "按钮Disable" : "按钮Enable"
            break
        }
        case "btnApiEvent":
        {
            let bFlag = wps.PluginStorage.getItem("ApiEventFlag")
            return bFlag ? "清除新建文件事件" : "注册新建文件事件"
            break
        }  
        // case "btnTest":
        //     {
        //     return "测试"
        // }
                
    }
    return ""
}

function OnNewDocumentApiEvent(doc){
    alert("新建文件事件响应，取文件名: " + doc.Name)
}


function OnTest(control){
    let rgn = wps.Selection
    let des = wps.Application.InputBox('提取到', '提取出生日期', null, null, null, null, null, 8)
    if (des){
        if (des.Count == rgn.Count){
            console.log("当前选中的单元格数量" + rgn.Count)
            // 1048576对应 xlsx格式，65536对应 xls格式
            if (rgn.Count == 1048576 || rgn.Count == 65536) {
                console.log("当前选中的单元格数量1048576个")
                e = rgn.End(4) //End(4)表示下方向
                row = e.Row
                col = e.Column
                for (let i = 1; i <= row; i++){
                    if (rgn.Item(i).Formula.length == 18){
                        des.Item(i).Formula = rgn.Item(i).Formula.substr(6,8)
                    }
                }
            }else{
                for (let i = 1; i <= rgn.Count; i++){
                    des.Item(i).Formula = rgn.Item(i).Formula.substr(6,8)
                }
            }
        }
    }else{
        wps.alert("取消")
        return false
    }
    return true
}


function OnBorderSetup(rgn){
    border = {
        "top":wps.Enum.xlEdgeTop,
        "bottom":wps.Enum.xlEdgeBottom,
        "left":wps.Enum.xlEdgeLeft,
        "right":wps.Enum.xlEdgeRight,
        "insideHorizontal":wps.Enum.xlInsideHorizontal,
        "insideVertical":wps.Enum.xlInsideVertical,
    }
    for (var i=1;i<=rgn.Count;i++){
        for (let key in border){
            (obj=>{
                obj.Weight = wps.Enum.xlThin;
                obj.LineStyle = wps.Enum.xlContinuous;
                obj.ColorIndex = wps.Enum.xlColorIndexAutomatic;
            })(rgn.Item(i).Borders.Item(border[key]));
        }        
    }

}

function OnPageSetup(){
    (obj=>{
        obj.Orientation = wps.Enum.xlPortrait;
        obj.Zoom = 100;
        obj.LeftMargin = 35;
        obj.RightMargin = 35;
        obj.TopMargin = 35;
        obj.BottomMargin = 35;
        obj.HeaderMargin = 0;
        obj.FooterMargin = 0;
        obj.PaperSize = wps.Enum.xlPaperA4;
    })(wps.ActiveSheet.PageSetup);

    wps.Columns.Item("A:A").ColumnWidth = 8.820000;
    wps.Columns.Item("B:B").ColumnWidth = 15.910000;
    wps.Columns.Item("C:C").ColumnWidth = 5;
    wps.Columns.Item("D:D").ColumnWidth = 8.820000;
    wps.Columns.Item("E:E").ColumnWidth = 15.910000;
    wps.Columns.Item("F:F").ColumnWidth = 5;
    wps.Columns.Item("G:G").ColumnWidth = 8.820000;
    wps.Columns.Item("H:H").ColumnWidth = 15.910000;


    wps.Cells.Font.Size = 11;       // 设置字体大小
    wps.Cells.Font.Name = "宋体";   // 设置字体
    wps.Cells.RowHeight = 14.6;     // 设置行高
    wps.Cells.NumberFormatLocal = "@"; // 设置单元格为文本格式
	wps.Cells.VerticalAlignment = wps.Enum.xlVAlignCenter;      // 设置垂直对齐方式
	wps.Cells.HorizontalAlignment = wps.Enum.xlHAlignCenter;    // 设置水平对齐方式
}

function OnAddPage(){
    sheetNums = wps.Worksheets.Count
    wps.Worksheets.Add(null,wps.Worksheets.Item(sheetNums));
}

function OnInit(){
    let stdName = wps.InputBox("学生的姓名列",null, null, null, null, null, null, 8)
    let stdClass = wps.InputBox("学生的班级列",null, null, null, null, null, null, 8)
    let stdExamHall = wps.InputBox("学生的考场列",null, null, null, null, null, null, 8)
    let stdExamSeat = wps.InputBox("学生的座位列",null, null, null, null, null, null, 8)
    let stdExamNum = wps.InputBox("学生的考号列",null, null, null, null, null, null, 8)

    row = stdName.End(4).Row
    let stdData = []
    for(let i=1;i<=row;i++){
        stdData.push({"姓名":stdName.Item(i).Formula,"班级":stdClass.Item(i).Formula,"考场":stdExamHall.Item(i).Formula,"座位号":stdExamSeat.Item(i).Formula,"考号":stdExamNum.Item(i).Formula})
    }
    return stdData
}


function OnExportBorder(row,col = 0){
    for(let i=1;i<=8;i=i+3){
        console.log(row,col + i)
        wps.Cells.Item(row,col + i).Formula = "姓名"
        wps.Cells.Item(row+1,col + i).Formula = "班级"
        wps.Cells.Item(row+2,col + i).Formula = "考场"
        wps.Cells.Item(row+3,col + i).Formula = "座位号"
        wps.Cells.Item(row+4,col + i).Formula = "考号"        
        OnBorderSetup(wps.Range(wps.Cells.Item(row,i), wps.Cells.Item(row+4,i+1)))
    }
}


function OnInputData(stdName,stdClass,stdExamHall,stdExamSeat,stdExamNum,rgn){
    rgn.Formula = stdName
    rgn.Offset(1).Formula = stdClass
    rgn.Offset(2).Formula = stdExamHall
    rgn.Offset(3).Formula = stdExamSeat
    rgn.Offset(4).Formula = stdExamNum
}

function OnUnique(control){
    let rgn = wps.Selection
    position = wps.InputBox("放置数据的位置",null, null, null, null, null, null, 8)
    arr = []
    if (rgn.Count == 1048576 || rgn.Count == 65536) {
        console.log("当前选中的单元格数量1048576个")
        e = rgn.End(4) //End(4)表示下方向
        row = e.Row
        col = e.Column
        rgn = wps.Range(wps.Cells.Item(1,col), wps.Cells.Item(row,col))
    }

    for (let i=1;i<=rgn.Rows.Count;i++){
        for(let j=1;j<=rgn.Columns.Count;j++){
            if(rgn.Item(i,j).Formula){
                if (!arr.includes(rgn.Item(i,j).Formula)){
                    arr.push(rgn.Item(i,j).Formula)
                }
            }
        }
    }
    
    console.log(arr);
    
    for(let i=0;i<arr.length;i++){
        position.Item(i+1).Formula = arr[i]
    }
    return true
}



